const mongoose = require('mongoose');

const connectDB = async () => {
    try {
        // 构建MongoDB连接URI
        const uri = `mongodb://${process.env.MONGODB_USERNAME}:${encodeURIComponent(process.env.MONGODB_PASSWORD)}@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DATABASE}?authSource=admin`;

        const conn = await mongoose.connect(uri, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        });

        console.log(`MongoDB 已连接: ${conn.connection.host}`);
        
        // 监听连接错误
        mongoose.connection.on('error', err => {
            console.error('MongoDB 连接错误:', err);
        });

        mongoose.connection.on('disconnected', () => {
            console.warn('MongoDB 连接断开');
        });

    } catch (error) {
        console.error('MongoDB 连接失败:', error);
        process.exit(1);
    }
};

module.exports = connectDB; 